package com.ti.srpglife.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.HashMap;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.XMLEvent;

public class Stats {

	// used to be sure we only import each file once
	private static HashMap<String,InputStream> used = new HashMap<String,InputStream>();
	
	/**
	 * Gets the stats from an .xml file for use in the units
	 * @param values
	 * @param stats
	 * @throws FileNotFoundException
	 * @throws XMLStreamException
	 */
	public static void setup(HashMap<String, String> values, String stats) throws FileNotFoundException, XMLStreamException {
		XMLInputFactory inputFactory = XMLInputFactory.newInstance();
		InputStream in;
		
		if(used.containsKey(stats))
		{
			in = used.get(stats);
		}
		else
			in = new FileInputStream(stats);
		
		// Setup a new eventReader
		XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
		
		// Read the XML document
		String lastkey = "";
		Integer lastvalue = 0;
		
		boolean readytoset = false;
		
		while (eventReader.hasNext()) {
	        XMLEvent event = eventReader.nextEvent();
	        
	        if(event.isStartElement()){
	        	lastkey = event.asStartElement().getName().toString();
	        	readytoset = true;
	        }
	        if(event.isCharacters() && readytoset){
	        	values.put(lastkey, event.asCharacters().getData()); 
	        	readytoset = false;
	        }
		}
	}
	
	 /**
	  *This will dump stats from the used map thereby allowing it to refresh on the next call of setup
	  *	be sure to dump stats whenever a character's base stats change! 
	  *	(modifiers and effects will be applied elsewhere)
	  *
	  * @param stats
	  */
	public static void refresh(String stats)
	{
		if(used.containsKey(stats))
			used.remove(stats);
	}

}
